<?php
/**
 * Created by PhpStorm.
 * User: allen
 * Date: 2019/3/8
 * Time: 10:38
 */
namespace app\admin\controller;

use app\admin\model\MchWithdraw;
use app\admin\model\ProxyMoney;
use app\admin\model\ProxyWithdraw;
use app\index\model\LotteryLog;
use think\App;
use Naixiaoxin\ThinkWechat\Facade;
use think\Db;

class Pay extends Base {

    protected static $payment  = null;

    public function __construct(App $app = null){
        parent::__construct($app);
        self::$payment = Facade::payment();
    }

    /**
     * 创建订单
     * @param string $title
     * @param int $fee
     * @param int $type   1vip,2充值
     * @return \think\Response|\think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function create_order($title='',$fee=0,$type=1){
        if(!$title){
            return json(['code'=>1,'msg'=>'请填写订单主题']);
        }
        $site = session('_site');
        if(!$site){
            return $this->__e('请重新登录');
        }
        if($type==1){
            $fee = $site['vip'];
        }else{
            if(!$fee){
                return json(['code'=>1,'msg'=>'请填写订单金额']);
            }
        }
        $uid = session('mc_id');
        $_data = $order = [
            'body' => $title,
            'out_trade_no' => build_order_no(),
            'total_fee' => $fee * 100,
            'trade_type' => 'NATIVE'
        ];
        $_data['create_time']=time();
        $_data['title']=$title;
        $_data['total_fee'] = $fee;
        $_data['mc_id'] = $uid;
        $_data['type'] = $type;
        $_data['status'] = 1;
        unset($_data['body']);
        $rechage = new \app\admin\model\Rechange();
        if(!$rechage->insert($_data)){
            return $this->__e('订单创建失败,请稍后再试');
        }
        $result = self::$payment->order->unify($order);
        return json(['status'=>1,'data'=>$result['code_url'],
            'out_trade_no'=>$_data['out_trade_no']]);
    }

    /**
     * @param string $out_trade_no
     * @return \think\response\Json
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function query_order($out_trade_no=''){
        if(!$out_trade_no){
            return json(['code'=>1,'msg'=>'请填写查询单号']);
        }
        $rechage = new \app\admin\model\Rechange();
        $order = $rechage
            ->where('out_trade_no','eq',$out_trade_no)
            ->find();
        if(!$order){
            return json(['code'=>1,'msg'=>'查询订单不存在']);
        }
        $result = self::$payment->order
            ->queryByOutTradeNumber($out_trade_no);
        if($result['trade_state']=='SUCCESS' && $result['result_code']=='SUCCESS'){
            Db::startTrans();
            $result = $rechage->where('id','eq',$order['id'])
                ->update([
                    'id'=> $order['id'],
                    'payment_trade_no'=>$result['transaction_id'],
                    'finish_time'=>time(),
                    'payment_notify_time'=>$result['time_end'],
                    'payment_trade_status'=>$result['trade_state_desc'],
                    'status'=>2
                ]);
            $mch = new \app\admin\model\Mch();
            $_mch = $mch->get($order['mc_id']);
            $name = "商户【{$_mch['name']}】，充值VIP";
            $proxy = new \app\admin\model\Proxy();
            $result1 = $proxy->
                getVipMoney($name,0,$_mch['id'],$order['total_fee'],$out1);
            $_mch->is_vip = 1;
            $result2 = $_mch->save();
            if($result && $result1 && $result2){
                Db::commit();
                return json(['code'=>0,'msg'=>'支付成功']);
            }else{
                Db::rollback();
                return json(['code'=>1,'msg'=>'']);
            }
        }else{
            return json(['code'=>1,'msg'=>'']);
        }
    }

    /**
     * 红包查询
     * @param string $order_id
     * @param string $type
     * @return \think\Response|\think\response\View
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function redpack_query($order_id='',$type=''){
        if(request()->isGet()){
           return view('redpack/query');
        }
        if(!$order_id || $type){
            return $this->__e(1,'缺少参数');
        }
        $result = self::$payment->redpack->info($order_id);
        if($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS'){
            if($type=='lottery_log'){
                $log = new LotteryLog();
                $log->decMoneyByOrderId($order_id,$result['status'],$result['return_msg'],$result['hblist'],$out);
            }elseif($type=='proxy_withdraw'){
                $log = new ProxyWithdraw();
                $log->decMoneyByOrderId($order_id,$result['status'],$result['return_msg'],$result['hblist'],$out);
            }elseif ($type=='mch_withdraw'){
                $log = new MchWithdraw();
                $log->decMoneyByOrderId($order_id,$result['status'],$result['return_msg'],$result['hblist'],$out);
            }
        }
        $json = json_encode($result);
        $str = _format_json($json);
        return $this->__s('查询成功',['json'=>$str]);
    }
}